#include "ad_studentmgrlist.h"
#include "ui_ad_studentmgrlist.h"

#include "ST_onestudentinfo.h"

AD_StudentMgrList::AD_StudentMgrList(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AD_StudentMgrList)
{
    ui->setupUi(this);

    QStringList head = {"学号","姓名","班级","辅导员","平均绩点"};
    TOOLS->setTableHead(ui->tableWidget,head);

    ui->comboBox->addItems({"学号","姓名","班级"});
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    connect(ui->tableWidget,&QTableWidget::doubleClicked,[=](const QModelIndex &index){
        qDebug()<<index;
        PAGEJUMP->setPage(DK_ST_OneStudentInfo);
        auto wgt = qobject_cast<ST_OneStudentInfo*>(PAGEJUMP->getPage(DK_ST_OneStudentInfo));
        if(wgt){
            wgt->setDataFromID(ui->tableWidget->model()->index
                        (index.row(),0).data().toString().toInt());
        }
    });
}

AD_StudentMgrList::~AD_StudentMgrList()
{
    delete ui;
}



void AD_StudentMgrList::on_showAllWarningStudentBtn_clicked()
{
    auto students = DB->getAllStudentInfo("avgGPA < 2.5");
    setDataToTable(students);
}


void AD_StudentMgrList::on_showAllStudentBtn_clicked()
{
    auto students = DB->getAllStudentInfo();
    setDataToTable(students);
}


void AD_StudentMgrList::on_exportAllWarningBtn_clicked()
{
    on_showAllWarningStudentBtn_clicked();

    on_pushButton_clicked();
}


void AD_StudentMgrList::on_exportAllStudentBtn_clicked()
{
    on_showAllStudentBtn_clicked();

    on_pushButton_clicked();
}

void AD_StudentMgrList::setDataToTable(const QList<DB_View_StudentInfo> &data)
{
    ui->tableWidget->setRowCount(data.count());

   for(int r = 0;r<data.count() ; r++){
       auto&& cur = data[r];

       QString info = "%0,%1,%2,%3,%4";
       info = info.arg(cur.id)
               .arg(cur.name)
               .arg(cur.className)
               .arg(cur.consultantName)
               .arg(cur.avgGPA);

       QStringList curStrs = info.split(",");

       for(int c = 0 ; c< curStrs.count();c++){
           ui->tableWidget->setItem(r,c,new  QTableWidgetItem(curStrs[c]));
       }
   }
}


void AD_StudentMgrList::on_queryBtn_clicked()
{
    auto info = ui->lineEdit->text();

    QString str = "";
    // 学号
    if(ui->comboBox->currentIndex() == 0){
        str = QString("id = %1").arg(info);
    }
    // 姓名
    else if(ui->comboBox->currentIndex() == 1){
        str = QString("name like \"%%1%\"").arg(info);
    }
    // 班级
    else if(ui->comboBox->currentIndex() == 2){
        str = QString("className like \"%%1%\"").arg(info);
    }

    auto students = DB->getAllStudentInfo(str);
    setDataToTable(students);
}


void AD_StudentMgrList::on_pushButton_clicked()
{
    auto path = TOOLS->openCSVSaveDialog();
    CSV->tabelSaveFile(ui->tableWidget,path);
}

